package com.sftz.modules.minapp.personal.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.google.common.collect.Lists;
import com.sftz.assets.entities.InstitutionStudentFormValueEntity;
import com.sftz.assets.entities.SUserEntity;
import com.sftz.assets.entities.SUserInfoEntity;
import com.sftz.assets.entities.UserTickEntity;
import com.sftz.assets.enums.SexEnum;
import com.sftz.assets.enums.SkinColorEnum;
import com.sftz.framework.constants.CommonConstants;
import com.sftz.modules.minapp.personal.dto.StudentFormValueDto;
import com.sftz.modules.minapp.personal.form.UserInfoStrForm;
import com.sftz.modules.minapp.user.cache.RedissionUserCache;
import com.uxuexi.core.common.util.BeanUtil;
import com.uxuexi.core.common.util.EnumUtil;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.web.base.service.BaseService;
import com.uxuexi.core.web.chain.support.JsonResult;

/**
 * 学院管理  修改密码
 * @author 郝振斌
 *
 * 2017年12月19日
 */
@IocBean
public class PersonalSetViewService extends BaseService<SUserEntity> {
	private static final Log log = Logs.get();

	@Inject
	private StudentFormService studentFormService;

	@Inject
	private StudentFormViewService studentFormViewService;
	
	private static final String constantVal = "请选择";

	public Object searchBasicInfo(String token) {
		Integer userId = RedissionUserCache.getUserId(token);
		Map<String, Object> valueMap = new HashMap<String, Object>();
		Map<String, String> sex = EnumUtil.enum2(SexEnum.class);
		Map<String, String> skinColor = EnumUtil.enum2(SkinColorEnum.class);
		valueMap.put("sex", sex);
		valueMap.put("skinColor", skinColor);
		
		SUserInfoEntity fetchInfo = dbDao.fetch(SUserInfoEntity.class, Cnd.where("userId", "=", userId));
		if(!Util.isEmpty(fetchInfo)){
			
			String birThAddress = fetchInfo.getBirThAddress();
			String homeAddress = fetchInfo.getHomeAddress();
			String[] birThArr = birThAddress.split(",");
			String bStr = birThArr[0];
			if(!Util.isEmpty(bStr)){
				bStr = addSet(bStr);
				birThArr[0] = bStr;
				if("null".equals(birThArr[1])){
					birThArr[1] = constantVal;
				}
				if("null".equals(birThArr[2])){
					birThArr[2] = constantVal;
				}
				String s1 = StringUtils.join(birThArr, ",");
				fetchInfo.setBirThAddress(s1);
			}
			String[] homeArr = homeAddress.split(",");
			String hStr = homeArr[0];
			if(!Util.isEmpty(hStr)){
				hStr = addSet(hStr);
				homeArr[0] = hStr;
				if("null".equals(homeArr[1])){
					homeArr[1] = constantVal;
				}
				if("null".equals(homeArr[2])){
					homeArr[2] = constantVal;
				}
				String s1 = StringUtils.join(homeArr, ",");
				fetchInfo.setHomeAddress(s1);
			}
		}
		
		valueMap.put("info", fetchInfo);
		//查询机构必填项
		Map<String, Object> insFormVal = studentFormService.queryFormInfo(userId,
				CommonConstants.INSTITUTION_STUDENT_FORM_ITEM_INSTITUTIONID);

		List<StudentFormValueDto> formValue = (List<StudentFormValueDto>) insFormVal.get("formValue");
		if (Util.isEmpty(formValue)) {
			formValue = (List<StudentFormValueDto>) insFormVal.get("itemList");
		}
		valueMap.put("formValue", Json.toJson(formValue));
		return valueMap;
	}

	public Object saveBasicInfo(String form, String token) {
		Integer userId = RedissionUserCache.getUserId(token);
		UserInfoStrForm userInfoStrForm = Json.fromJson(UserInfoStrForm.class, form);
		String id = userInfoStrForm.getId();
		userInfoStrForm.setUserId(userId);
		
		//分解数据
		String name = userInfoStrForm.getName();
		String idCard = userInfoStrForm.getIdCard();
		String job = userInfoStrForm.getJob();
		String workY = userInfoStrForm.getWorkY();
		String[] nameArr = itemVal(name);
		String[] idCardArr = itemVal(idCard);
		String[] jobArr = itemVal(job);
		String[] workYarr = itemVal(workY);
		//添加、修改机构表单项的值
		List<InstitutionStudentFormValueEntity> toAdd = Lists.newArrayList();
		InstitutionStudentFormValueEntity nameE = new InstitutionStudentFormValueEntity();
		nameE.setUserId(userId);
		nameE.setItemId(Integer.valueOf(nameArr[1]));
		nameE.setItemValue(nameArr[0]);
		toAdd.add(nameE);
		InstitutionStudentFormValueEntity idCardE = new InstitutionStudentFormValueEntity();
		idCardE.setUserId(userId);
		idCardE.setItemId(Integer.valueOf(idCardArr[1]));
		idCardE.setItemValue(idCardArr[0]);
		toAdd.add(idCardE);
		InstitutionStudentFormValueEntity jobE = new InstitutionStudentFormValueEntity();
		jobE.setUserId(userId);
		jobE.setItemId(Integer.valueOf(jobArr[1]));
		jobE.setItemValue(jobArr[0]);
		toAdd.add(jobE);
		InstitutionStudentFormValueEntity workYE = new InstitutionStudentFormValueEntity();
		workYE.setUserId(userId);
		workYE.setItemId(Integer.valueOf(workYarr[1]));
		workYE.setItemValue(workYarr[0]);
		toAdd.add(workYE);
		boolean s = studentFormService.saveOrUpdate(toAdd);
		if(s){
			String[] birThAddress = userInfoStrForm.getBirThAddress();
			String[] homeAddress = userInfoStrForm.getHomeAddress();
			StringBuffer birstr = new StringBuffer();
			StringBuffer homestr = new StringBuffer();
			String birthday = userInfoStrForm.getBirthday();
			if("请选择".equals(birthday)){
				birthday = "";
			}
			String str = "";
			for (int i = 0; i < birThAddress.length; i++) {
				if(i == 0){
					str = birThAddress[i];
					if(str.contains("市") || str.contains("省")){
						str = birThAddress[i].substring(0, birThAddress[i].length()-1);
					}else if(str.indexOf("内蒙") != -1 || str.indexOf("西藏") != -1){
						str = birThAddress[i].substring(0, birThAddress[i].length()-3);
					}else if(str.indexOf("新疆") != -1 ){
						str = birThAddress[i].substring(0, birThAddress[i].length()-6);
					}else if(str.indexOf("广西") != -1){
						str = birThAddress[i].substring(0, birThAddress[i].length()-5);
					}else if(str.indexOf("宁夏") != -1){
						str = birThAddress[i].substring(0, birThAddress[i].length()-5);
					}else if(str.contains("特别行政区")){
						str = birThAddress[i].substring(0, birThAddress[i].length()-5);
					}
				}else{
					str = birThAddress[i];
					if(Util.isEmpty(str) || str == null){
						str = "请选择";
					}
				}
				birstr.append(str + ",");
			}
			for (int i = 0; i < homeAddress.length; i++) {
				if(i == 0){
					str = homeAddress[i];
					if(str.contains("市") || str.contains("省")){
						str = homeAddress[i].substring(0, homeAddress[i].length()-1);
					}else if(str.indexOf("内蒙") != -1 || str.indexOf("西藏") != -1){
						str = homeAddress[i].substring(0, homeAddress[i].length()-3);
					}else if(str.indexOf("新疆") != -1 ){
						str = homeAddress[i].substring(0, homeAddress[i].length()-6);
					}else if(str.indexOf("广西") != -1){
						str = homeAddress[i].substring(0, homeAddress[i].length()-5);
					}else if(str.indexOf("宁夏") != -1){
						str = homeAddress[i].substring(0, homeAddress[i].length()-5);
					}else if(str.contains("特别行政区")){
						str = homeAddress[i].substring(0, homeAddress[i].length()-5);
					}
				}else{
					str = homeAddress[i];
					if(Util.isEmpty(str) || str == null){
						str = "请选择";
					}
				}
				homestr.append(str + ",");
			}
			String birThAddressStr = birstr.substring(0, birstr.length()-1).toString();
			String homeAddressStr = homestr.substring(0, homestr.length()-1).toString();
			SUserInfoEntity enty = null;
			int res = 0;
			if (Util.isEmpty(id)) {
				SUserInfoEntity suser = new SUserInfoEntity();
				if(!Util.isEmpty(userInfoStrForm.getSex())){
					suser.setSex(Integer.valueOf(userInfoStrForm.getSex()));
				}
				if(!Util.isEmpty(userInfoStrForm.getBirthday())){
					try {
						suser.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(userInfoStrForm.getBirthday()));
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(!Util.isEmpty(userInfoStrForm.getConstellation())){
					suser.setConstellation(userInfoStrForm.getConstellation());
				}
				if(!Util.isEmpty(userInfoStrForm.getConsteurl())){
					suser.setConsteurl(userInfoStrForm.getConsteurl());
				}
				if(!Util.isEmpty(userInfoStrForm.getHeight())){
					suser.setHeight(Double.valueOf(userInfoStrForm.getHeight()));
				}
				if(!Util.isEmpty(userInfoStrForm.getWeight())){
					suser.setWeight(Double.valueOf(userInfoStrForm.getWeight()));
				}
				if(!Util.isEmpty(userInfoStrForm.getSkinColor())){
					suser.setSkinColor(Integer.valueOf(userInfoStrForm.getSkinColor()));
				}
				
				if(!Util.isEmpty(userInfoStrForm.getBirThAddress())){
					suser.setBirThAddress(birThAddressStr);
				}
				if(!Util.isEmpty(userInfoStrForm.getHomeAddress())){
					suser.setHomeAddress(homeAddressStr);
				}
				suser.setUserId(userId);
				enty = dbDao.insert(suser);//新增操作
			} else {
				res = dbDao.update(
						SUserInfoEntity.class,
						Chain.make("sex", userInfoStrForm.getSex())
								.add("birthday", birthday)
								.add("constellation", userInfoStrForm.getConstellation())
								.add("consteurl", userInfoStrForm.getConsteurl()).add("weight", userInfoStrForm.getWeight())
								.add("height", userInfoStrForm.getHeight()).add("skinColor", userInfoStrForm.getSkinColor())
								.add("birThAddress", birThAddressStr)
								.add("homeAddress", homeAddressStr), Cnd.where("id", "=", id));
			}
			if (!Util.isEmpty(enty) || res > 0) {
				return true;
			} else {
				return false;
			}
		}else{
			return false;
		}
	}

	/**
	 * 判断重复登陆
	 * @param request
	 * @return
	 */
	public Object checkout(HttpServletRequest request,String token) {
		Integer userId = RedissionUserCache.getUserId(token);
		Integer res = 1;
		if (Util.isEmpty(userId)) {
			String cookieName = "myCookie";
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					if (cookie.getName().equals(cookieName)) {
						res = 0;
						break;
					}
				}
			}

		} else {
			UserTickEntity fetch = dbDao.fetch(UserTickEntity.class, Cnd.where("userId", "=", userId));
			if (!Util.isEmpty(fetch)) {
				res = 0;
			}
		}
		return res;

	}

	/**
	 * 保存用户反馈信息
	 * @param userTickDto
	 * @param session
	 * @param request
	 * @return
	 */
	@Aop("txDb")
	public Object saveInfo(String content, String confirmCode, HttpServletResponse response, HttpSession session,String token) {
		Integer wxUId = RedissionUserCache.getUserId(token);
		String sessionId = session.getId();
		Date date = new Date();
		String userId;
		/*if (!Util.isEmpty(confirmCode)) {
			String recode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
			String vCode = confirmCode;
			if (Util.isEmpty(recode) || Util.isEmpty(vCode) || !recode.equalsIgnoreCase(vCode)) {
				session.setAttribute(SessionKeys.USERLOGINMESSAGE, "验证码不正确!");
				return 0;
			}
		}*/
		if (Util.isEmpty(wxUId)) {//未登录用户
			userId = sessionId;
		} else {
			userId = String.valueOf(wxUId);
		}

		List<UserTickEntity> tobeAdd = new ArrayList<UserTickEntity>();
		Map<String,Object> dto = (Map) Json.fromJson(content);
	
		UserTickEntity entity = new UserTickEntity();
		BeanUtil.copyProperties(dto, entity);
		entity.setUserId(userId);

		String aId = (String) dto.get("answerId");
		if (Util.isEmpty(aId)) {
			aId = "-1";
		}
		entity.setQuestionId(Integer.valueOf((String) dto.get("questionId")));
		entity.setAnswerId(aId);
		entity.setSubmitDate(date);
		tobeAdd.add(entity);
		dbDao.insert(tobeAdd);
		return JsonResult.success("success");
	}
	
	public String[] itemVal(String da){
		String[] arr = da.split("_");
		return arr;
	}
	
	public String addSet(String str1){
		if(str1.indexOf("内蒙") != -1 || str1.indexOf("西藏") != -1){
			str1 += "自治区";
		}else if(str1.indexOf("新疆") != -1 ){
			str1 += "维吾尔自治区";
		}else if(str1.indexOf("广西") != -1){
			str1 += "壮族自治区";
		}else if(str1.indexOf("宁夏") != -1){
			str1 += "回族自治区";
		}else if(str1.indexOf("北京") != -1 || str1.indexOf("天津") != -1 || str1.indexOf("重庆") != -1 || str1.indexOf("上海") != -1){
			str1 += "市";
		}else if(str1.indexOf("香港") != -1 || str1.indexOf("澳门") != -1){
			str1 += "特别行政区";
		}else{
			str1 += "省";
		}
		
		return str1;
	}
}